package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CorpusStatsDistribution extends ResultFilter {

	@Override
	public void computeResult(ResultSet rs) throws SQLException, IOException {
		rs.first();
		
		Set<String> projects = new HashSet<String>();
		Map<String,Integer> stats_last_libs = new HashMap<String, Integer>();
		Map<String,Integer> stats_nb_months = new HashMap<String, Integer>();

		while (rs.next()){
			String project = rs.getString("PROJECT");
			projects.add(project);
			String libs = rs.getString("LAST_LIBS");
			String nb_months = rs.getString("LAST_NBMONTHS");
			libs = libs.replaceAll("\\]","").replaceAll("\\[", "").replaceAll(" ", "");
			stats_last_libs.put(project, Utils.filterLibs(libs.split("\\,")).size());
			stats_nb_months.put(project, Integer.parseInt(nb_months));
		}

		PrintStream ps = new PrintStream(System.out);
		ps.println(projects.size()+" projects");
		ps.println("******** MONTHS DISTRIBUTION *********");
		List<List<String>> distrib_months = new ArrayList<List<String>>();
		for(int i = 0 ; i < 45 ; i++){
			distrib_months.add(new ArrayList<String>());
		}
		int limit=12;
		for(String project : stats_nb_months.keySet()) {
			int part = stats_nb_months.get(project)/limit;
			distrib_months.get(part).add(project);
		}

		for(int i = 0 ; i < 45 ; i++){
			ps.println("["+i*limit+","+((i*limit)+limit)+"],"+distrib_months.get(i).size()+ " ("+Utils.formatDouble(((double)(distrib_months.get(i).size())/(double)projects.size())*100)+" %)");
		}

		ps.println("******** LIBRARIES DISTRIBUTION *********");
		List<List<String>> distrib_libs = new ArrayList<List<String>>();
		for(int i = 0 ; i < 30 ; i++){
			distrib_libs.add(new ArrayList<String>());
		}
		int limit_libs=5;
		for(String project : stats_last_libs.keySet()) {
			int part = stats_last_libs.get(project)/limit_libs;
			distrib_libs.get(part).add(project);
		}
		for(int i = 0 ; i <  30 ; i++){
			ps.println("["+i*limit_libs+","+((i*limit_libs)+limit_libs)+"],"+distrib_libs.get(i).size()+ " ("+Utils.formatDouble(((double)(distrib_libs.get(i).size())/(double)projects.size())*100)+" %)");
		}
		ps.close();
	}


	

}
